package com.lagou.demo.controller.interceptor;

import com.lagou.edu.mvcframework.annotations.LagouComponent;
import com.lagou.edu.mvcframework.annotations.LagouSecurity;
import com.lagou.edu.mvcframework.interceptor.LagouHandlerInterceptor;
import com.lagou.edu.mvcframework.pojo.Handler;
import com.lagou.edu.mvcframework.pojo.LogouModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@LagouComponent
public class SecurityInterceptor implements LagouHandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断方法上是否有注解@Security注解,如果有，以方法的注解为准，如果没有，以类上的注解为准
        Handler methodHandler= (Handler) handler;
        LagouSecurity lagouSecurity = ((Handler) handler).getMethod().getAnnotation(LagouSecurity.class);
        if(lagouSecurity==null){
            lagouSecurity =((Handler) handler).getController().getClass().getAnnotation(LagouSecurity.class);
        }
        String[] authUsers = lagouSecurity.value();
        if(null==authUsers||authUsers.length==0){
            return true;
        }
        String username = request.getParameter("username");
        for (String authUser : authUsers) {
            if(authUser.equalsIgnoreCase(username)){
                return true;
            }
        }
        response.getWriter().write("无权限访问");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, LogouModelAndView result) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
